﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using Newtonsoft.Json;

/// <summary>
/// 学习参考：https://geek-docs.com/csharp/csharp-tutorial/csharp-httpclient.html
///     https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=net-5.0
/// </summary>
namespace LearnCSharp_1
{
    class LearnHttpClient
    {
        public static async Task Main_LearnHttpClient(string[] args)
        {
            var client = new HttpClient();
            // 将GET请求作为异步操作发送到指定Uri。
            // await运算符会暂停对异步方法的评估，直到异步操作完成为止。
            var result = await client.GetAsync("http://192.168.56.1:8080/");
            Console.WriteLine(result.StatusCode);
            Console.ReadKey();

            var content = await client.GetStringAsync("http://192.168.56.1:8080/");
            Console.WriteLine(content);
            Console.ReadKey();

            var url = "http://192.168.56.1:8080/";
            result = await client.SendAsync(new HttpRequestMessage(HttpMethod.Head, url));
            Console.WriteLine(result);
            Console.ReadKey();

            /**
             * HTTP POST方法将数据发送到服务器，请求正文的类型由Content-Type标头指示。
             * 
             * $ dotnet add package Newtonsoft.Json
             * 
             * 我们需要添加Newtonsoft.Json包来处理JSON数据。
             */
            var person = new Person();
            person.Name = "John Doe";
            person.Occupation = "gardener";

            var json = JsonConvert.SerializeObject(person);
            var data = new StringContent(json, Encoding.UTF8, "application/json");
            var response = await client.PostAsync("https://httpbin.org/post", data);
            string res = response.Content.ReadAsStringAsync().Result;
            Console.WriteLine(res);
            Console.ReadKey();


        }

        class Person
        {
            public string Name { get; set; }
            public string Occupation { get; set; }

            public override string ToString()
            {
                return $"{Name}: {Occupation}";
            }
        }

        class Contributor
        {
            public string Login { get; set; }
            public short Contributions { get; set; }
            public override string ToString()
            {
                return $"{Login,20}: {Contributions} contributions";
            }
        }
    }
}
